import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../views/Login/login.vue'
import index from '../views/Home/index.vue'
import store from '@/store'
import erro from '@/views/404.vue'
Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Logins',
    component: Login
  },
  {
    path: '/login',
    name: 'Login',
    component: Login
  }, {
    path: '/home',
    name: 'home',
    component: index
    ,children:[]
  },{
    path:'*',
    name :'erro',
    component:erro
  }
]





const router = new VueRouter({
  routes
})

//路由守卫
router.beforeEach((to, from, next) => {
  if (to.path === "/login") {
    next();
  } else {
    if (sessionStorage.getItem("token")) {
      next();
    } else {
      next("/login")
    }
  }

})

// 动态路由
const tableRule = {
  path: '/table',
  name: 'table',
  component: () => import('@/views/tables')
}
const imageRule = {
  path: '/image',
  name: 'image',
  component: () => import('@/views/image')
}
const userRule = {
  path: '/users',
  name: 'users',
  component: () => import('@/views/users')
}
const ruleMapping = {
  table: tableRule,
  users: userRule,
  image: imageRule
}

//动态路由
export function initRouters(){
  //获取到vuex中的保存的用户的权限信息

   let leftList = store.state.leftList;
   console.log(leftList);

   console.log(router);
   let rouertConfig = router.options.routes;
   leftList.forEach(arr=>{
    arr.children.forEach(arr=>{
     let select =  ruleMapping[arr.path];
     select.meta = arr.rights;
      console.log(select);
      rouertConfig[2].children.push(select);
    })
   })
   console.log(rouertConfig)
   router.addRoutes(rouertConfig);
    


}
export default router
